package com.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.domain.cargo.Contract;
import com.domain.cargo.ContractExample;
import com.domain.vo.ContractProductVo;
import com.github.pagehelper.PageInfo;
import com.service.cargo.ContractProductService;
import com.service.cargo.ContractService;
import com.web.controller.BaseController;
import common.utils.DownloadUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract/")
//@DubboComponentScan
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ContractProductService contractProductService;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer size){
        /**
         * 细粒度划分,根据dgree进行区分
         *      degree=4:普通员工:添加条件-创建人
         *      degree=3:管理部门:添加条件-部门创建人
         *      degree=2:管理所有下属:添加条件-模糊查询"管理人员id开头%"
         */
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(companyId);

        Integer degree = loginUser.getDegree();
        if (degree == 4) {
            //追加sql语句:and create_by = #{id}
            criteria.andCreateByEqualTo(loginUser.getId());
        }else if(degree == 3){
            //追加sql语句:and create_dept = #{deptId}
            criteria.andCreateDeptEqualTo(loginUser.getDeptId());
        }else if(degree == 2){
            //追加sql语句:and create_dept like "#{id}%"
            criteria.andCreateDeptEqualTo(loginUser.getId() + "%");
        }
        PageInfo pageInfo = contractService.findAll(example, page, size);

        request.setAttribute("page", pageInfo);
        return "cargo/contract/contract-list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "cargo/contract/contract-add";
    }

    @RequestMapping("/edit")
    public String edit(Contract contract){
        contract.setCompanyId(companyId);
        contract.setCompanyName(companyName);


        if (StringUtils.isBlank(contract.getId())) {
            contract.setCreateBy(loginUser.getId());//将登录的用户id写入创建者
            contract.setCreateDept(loginUser.getDeptId());//设置部门id,在部门管理员处可以查询到
            contractService.save(contract);
        }else{
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-update";
    }

    @RequestMapping("/delete")
    public String delete(String id){
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping("/print")
    public String print(){
        return "cargo/print/contract-print";
    }

    @RequestMapping("/printExcel")
    //打印出货表
    public void printExcel(String inputDate) throws IOException {
        //通过日期查询所有对应的货物,封装为List<ContractProductVo>
        List<ContractProductVo> products =  contractProductService.findByShipTime(inputDate);
        //创建XSSFWorkbook对象
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建页
        XSSFSheet sheet = workbook.createSheet();
        //创建第一行,写标题
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        //2015-01 --> 2015年01月出货表
        cell.setCellValue(inputDate.replace("-", "年") + "月出货表");

        //创建第二行,写小标题字段
        row = sheet.createRow(1);
        //写字段,首位空,读取时,不写
        String[] strings = new String[]{"", "客户", "订单号", "货号", "数量", "工厂", "工厂交期", "船期", "贸易条款"};
        for (int i = 1; i < strings.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(strings[i]);
        }
        //循环写货物的数据
        int rowIndex = 2;//从第3行开始输出
        for (ContractProductVo product : products) {
            row = sheet.createRow(rowIndex);

            cell = row.createCell(1);
            cell.setCellValue(product.getCustomName());

            cell = row.createCell(2);
            cell.setCellValue(product.getContractNo());cell = row.createCell(3);
            
            cell.setCellValue(product.getProductNo());

            cell = row.createCell(4);
            cell.setCellValue(product.getCnumber());

            cell = row.createCell(5);
            cell.setCellValue(product.getFactoryName());

            cell = row.createCell(6);
            cell.setCellValue(product.getDeliveryPeriod());

            cell = row.createCell(7);
            cell.setCellValue(product.getShipTime());

            cell = row.createCell(8);
            cell.setCellValue(product.getTradeTerms());

            rowIndex++;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        new DownloadUtil().download(baos, response, inputDate.replace("-", "年") + "月出货表.xlsx");
    }

    @RequestMapping("/printExcelByTemplate")
    //打印出货表
    public void printExcelByTemplate(String inputDate) throws IOException {
        //获取模板路径
        String path = "F:\\HeiMaPeiXun\\资料\\SaaS案例\\SaaS-Export\\day10\\03-资料\\excel资源\\tOUTPRODUCT.xlsx";
        //通过日期查询所有对应的货物,封装为List<ContractProductVo>
        List<ContractProductVo> products =  contractProductService.findByShipTime(inputDate);
        //通过路径创建XSSFWorkbook对象
        XSSFWorkbook workbook = new XSSFWorkbook(path);
        //创建页
        XSSFSheet sheet = workbook.getSheetAt(0);
        //获取第一行,修改标题
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(1);
        //修改:2015-01 --> 2015年01月出货表
        cell.setCellValue(inputDate.replace("-", "年") + "月出货表");

        //获取第二行,写小标题字段
        /*
        row = sheet.getRow(1);
        //这里不用写,因为Excel表和要展示的数据相同
        String[] strings = new String[]{"", "客户", "订单号", "货号", "数量", "工厂", "工厂交期", "船期", "贸易条款"};
        for (int i = 1; i < strings.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(strings[i]);
        }
        */

        //循环写货物的数据
        int rowIndex = 2;
        //加入样式,读取数据区域的样式,应该是第3行
        row = sheet.getRow(2);
        CellStyle[] cellStyles = new CellStyle[9];
        for (int i = 1; i < 9; i++) {
            cell = row.getCell(i);
            cellStyles[i] = cell.getCellStyle();
        }
        for (ContractProductVo product : products) {
            row = sheet.createRow(rowIndex);

            cell = row.createCell(1);
            cell.setCellValue(product.getCustomName());
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(2);
            cell.setCellValue(product.getContractNo());
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(3);
            cell.setCellValue(product.getProductNo());
            cell.setCellStyle(cellStyles[3]);

            cell = row.createCell(4);
            cell.setCellValue(product.getCnumber());
            cell.setCellStyle(cellStyles[4]);

            cell = row.createCell(5);
            cell.setCellValue(product.getFactoryName());
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(6);
            cell.setCellValue(product.getDeliveryPeriod());
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(7);
            cell.setCellValue(product.getShipTime());
            cell.setCellStyle(cellStyles[7]);

            cell = row.createCell(8);
            cell.setCellValue(product.getTradeTerms());
            cell.setCellStyle(cellStyles[8]);

            rowIndex++;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        new DownloadUtil().download(baos, response, inputDate.replace("-", "年") + "月出货表.xlsx");
    }

    @RequestMapping("/toView")
    public String toView(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "/cargo/contract/contract-view";
    }
}
